import { onMounted, onUnmounted, ref } from 'vue'

/**
 * @description 获取浏览器窗口尺寸大小
 * @function useWindowSize()
 * @return object = { width, height }
 * @example
   <script setup lang="ts">
     const { width, height } = useWindowSize()
   </script>

   <template>
     <div>resize: {{width}}, {{height}}</div>
   </template>
 */
export const useWindowSize = (options = { includeScrollbar: true }) => {
  const { includeScrollbar } = options

  const width = ref(0)
  const height = ref(0)

  const getWindowSize = () => {
    if (includeScrollbar) {
      width.value = window.innerWidth
      height.value = window.innerHeight
    } else {
      width.value = window.document.documentElement.clientWidth
      height.value = window.document.documentElement.clientWidth
    }
  }

  onMounted(() => {
    window.addEventListener('resize', getWindowSize)
  })
  onUnmounted(() => {
    window.removeEventListener('resize', getWindowSize)
  })

  return {
    width,
    height
  }
}
